package com.rory.gooday.common.cron4j;

import com.jfinal.json.Json;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.cron4j.ITask;
import com.jfinal.plugin.redis.Redis;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

public class LoadTasksTask implements ITask {

    @Override
    public void stop() {
    }

    @Override
    public void run() {
        try {
            Redis.call(jedis -> {
                Set<String> keys = jedis.keys("task:*");
                if (!keys.isEmpty()) {
                    return jedis.del(keys.toArray(new String[0]));
                }
                return 0L;
            });
            // 注意：建议在memorial表的is_msg和open_count字段上建立复合索引
            // 防止数据量过大导致内存问题，实际使用中应考虑分页处理
            List<Record> tasks = Db.find("select * from task where is_msg = 1 and is_archiv = 0 and (flag = 1 or flag = 2) LIMIT 10000");
            System.out.println("重载任务：" + tasks.size());
            Map<LocalDateTime,List<Integer>> result = new HashMap<>();

            tasks.forEach(task -> {
                LocalDateTime dateTime = LocalDateTime.parse(task.getStr("task_time"));
                result.computeIfAbsent(dateTime, k -> new ArrayList<>()).add(Integer.valueOf(task.getStr("id")));
            });

            for (Map.Entry<LocalDateTime, List<Integer>> entry : result.entrySet()) {
                LocalDateTime dateTime = entry.getKey();
                long timestamp = dateTime.atZone(ZoneId.systemDefault()).toEpochSecond();
                List<Integer> ids = entry.getValue();
                System.out.println("task:"+dateTime.getYear()+dateTime.getMonthValue()+":"+dateTime.toString()+"/"+Json.getJson().toJson(ids));
                Redis.call(jedis -> {
                    return jedis.set("task:"+timestamp, Json.getJson().toJson(ids));
                });
            }
        } catch (Exception e) {
            // 添加异常处理，避免线程静默失败
            e.printStackTrace(); // 实际项目中应使用proper logging
        }
    }

}